package com.heima.leetcode.practice;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 94 二叉树的中序遍历
 * @date 2025/1/4 10:26
 */
public class E94 {

    /**
     * <h3>方法一：递归</h3>
     *
     * @param root 根节点
     * @return 中序遍历结果
     */
    public List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        inorderTraversal(root, result);
        return result;
    }

    /**
     * 递归
     *
     * @param root   根节点
     * @param result 遍历结果
     */
    private void inorderTraversal(TreeNode root, List<Integer> result) {
        if (root == null) return;
        inorderTraversal(root.left, result);
        result.add(root.val);
        inorderTraversal(root.right, result);
    }

    /**
     * <h3>方法二：迭代</h3>
     *
     * @param root 根节点
     * @return 中序遍历结果
     */
    public List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        TreeNode curr = root;
        TreeNode lastPop = null;
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.push(curr);
                curr = curr.left;
            } else {
                TreeNode last = stack.peek();
                if (last.right == null) { // 右子树为null
                    result.add(last.val);
                    lastPop = stack.pop();
                } else if (last.right == lastPop) { // 右子树已经遍历过了
                    lastPop = stack.pop();
                } else { // 待处理右子树
                    result.add(last.val);
                    curr = last.right;
                }
            }
        }
        return result;
    }
}
